#include"network.h"
#include"pthread_pool.h"

typedef cycle_p_c<Data> cycle;
//创建线程池
cycle pool;

//处理任务
void* haddle_c(void* arg)
{
    cycle *ptr=(cycle*)arg;
    
    while(1)
    {
        //先获取任务
        struct Data data=ptr->pop();
        //执行任务
        ptr->Handle_tasks(&data);
    }

    return NULL;
}


int main()
{
    //创建套接字
    int token = socket(AF_INET, SOCK_STREAM, 0);
    if(token==-1)
    {
        log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"错误码：%d,错误信息：%s",errno,strerror(errno));
        exit(LOG_LEVEL_SOCKET);
    }
    else
    {
        log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"socket is successful");
    }

    //绑定IP和端口
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));

    addr.sin_family=AF_INET;
    addr.sin_addr.s_addr=htonl(INADDR_ANY);
    addr.sin_port=htons(8080);

    int bin = bind(token,(const sockaddr*)&addr,sizeof(addr));
    if(bin==-1)
    {
        log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"错误码：%d,错误信息：%s",errno,strerror(errno));
        exit(LOG_LEVEL_BIND);
    }
    else
    {
        log_message(LOG_LEVEL_SUCCESS,__FILE__,__LINE__,"bind is successful");
    }

    //持续监听
    int ls = listen(token,10);
    if(ls==-1)
    {
        log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"错误码：%d,错误信息：%s",errno,strerror(errno));
        exit(LOG_LEVEL_LISTEN);
    }
    else
    {
        log_message(LOG_LEVEL_SUCCESS,__FILE__,__LINE__,"listen is successful");
    }

    struct sockaddr_in lock;
    memset(&lock, 0, sizeof(lock));
    socklen_t sz = sizeof(lock);

    char buffer[max_size]={0};
    struct Data data;
    while(1)
    {
        //持续接收请求
        int new_token = accept(token,(sockaddr*)&lock,&sz);
        if(new_token==-1)
        {
            log_message(LOG_LEVEL_INFO,__FILE__,__LINE__,"错误码：%d,错误信息：%s",errno,strerror(errno));
            exit(LOG_LEVEL_ACCEPT);
        }
        //读取信息
        ssize_t t =recv(new_token, buffer, sizeof(buffer)-1, 0);
        if(t>0)
        {
            pid_t t =fork();
            if(t>0)close(new_token);
            else
            {
                //创建线程池
                cycle *ptr=new cycle;
                //包装任务
                struct Data data;
                data._addr=lock.sin_addr;
                data._port=lock.sin_port;
                data._fd=new_token;
                data._ptr=buffer;
                //发送任务
                ptr->push_back(data);

                //任务执行线程
                pthread_t pthread_c;
                pthread_create(&pthread_c,NULL,haddle_c,ptr);
            }
        }
    }
    //回收子进程
    pid_t pid;
    while(pid=(waitpid(-1,NULL,WNOHANG))>0);
    //关闭服务端端点
    close(token);

    return 0;
}